# -*- coding: utf-8 -*-
import sys
import ast
import json
import requests
import re
import time

# 请求头部
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/82.0.4083.0 Safari/537.36",
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "accept-encoding": "gzip, deflate, br",
    "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-US;q=0.7",
    "Upgrade-Insecure-Requests": "1"
}
# 代理
proxy = {
    'http': 'http://127.0.0.1:1080',
    'https': 'http://127.0.0.1:1080'
}

'''
    获取ios捷近传递的参数
'''


def get_url():
    rawInput = sys.argv.__str__()
    listInput = ast.literal_eval(rawInput)

    # 判断ins地址，并获取
    ins_url = get_ins_url(listInput)
    if len(ins_url) > 0:
        return ins_url


'''
    从参数中获取地址
'''


def get_ins_url(input):
    if len(input) == 2:
        if 'https://www.instagram.com/' in input[1]:
            return input[1]
    # console.alert('提示', 'ins链接无效', hide_cancel_button=True, button1='确定')
    exit(1)


'''
    访问ins网页，获取资源链接
'''


def crawl(u):
    try:
        res = requests.get(u, headers=headers, proxies=proxy)
        patten = '(?<=window\\._sharedData = ).*(?=;<\\/script>)'
        result = re.search(patten, res.content.decode('utf-8'), flags=0)

        json_data = json.loads(result.group())

        shortcode_media = json_data['entry_data']['PostPage'][0]['graphql']['shortcode_media']

        result_urls = []

        # 是否为视频
        if shortcode_media['is_video']:
            result_urls.append(shortcode_media['video_url'])
        else:
            if 'edge_sidecar_to_children' in shortcode_media:
                edges_ = shortcode_media['edge_sidecar_to_children']['edges']
                for edg in edges_:
                    node_ = edg['node']
                    if node_['is_video']:
                        result_urls.append(node_['video_url'])
                    else:
                        resources_ = node_['display_resources']
                        # 取display_resources数组最大像素的图片
                        result_urls.append(resources_[len(resources_) - 1]['src'])
            else:
                resources_ = shortcode_media['display_resources']
                result_urls.append(resources_[len(resources_) - 1]['src'])

        return None if len(result_urls) == 0 else result_urls
    except Exception as e:
        raise e


'''
    下载图片
'''


def download_resource(paths):
    for path in paths:
        res = requests.get(path, headers=headers, proxies=proxy, stream=True)
        print(res.content)
        # if res.status_code == 200:
        #     # 下载到路径
        #     download_path = 'C:\\Users\\limuyi\\Desktop\\ins\\' + str(round(time.time() * 1000)) + '.jpg'
        #     with open(download_path, 'wb') as file:
        #         file.write(res.content)
        # del res


'''
    入口函数
'''
if __name__ == '__main__':

    # return 'https://www.instagram.com/p/B9uMFHqgrQZ/?igshid=qdgsinpbl2qe' # video
    # return 'https://www.instagram.com/p/B9Y4epbp4iS/?igshid=12034fmzcf9aq'  # media
    # 'https://www.instagram.com/p/B9lNta9ASja/?igshid=1odidu6lo928j'  # image

    url = get_url()
    if len(url) > 0:
        urls = crawl(url)
        if len(urls) > 0:
            print(urls)
            # download_resource(urls)
        else:
            # console.alert('提示', '路径解析失败', hide_cancel_button=True, button1='确定')
            print('路径解析失败')
    else:
        # console.alert('提示', 'ins链接有误', hide_cancel_button=True, button1='确定')
        print('ins链接有误')
